﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace WeBSF.ToolComm
{
    public class ConvertHelper
    {
        public static ConvertHelper converter = new ConvertHelper();

        /// <summary>
        /// 获取远程图片的数据流
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public Stream GetYCStream(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            MemoryStream ms = new MemoryStream();
            return response.GetResponseStream();
        }

        /// <summary>
        /// 图片流保存为图片
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public string SaveYCStream(Stream stream, Dictionary<string,string> filename)
        {
            Bitmap _Bitmap = (Bitmap)Bitmap.FromStream(stream);
            MemoryStream ms = new MemoryStream();
            _Bitmap.Save(ms, ImageFormat.Jpeg);
            string _sPath = filename["dirpath"].ToString();
            string _filename = filename["filename"].ToString();
            if (!Directory.Exists(_sPath))
            {
                Directory.CreateDirectory(_sPath);
            }
            using (Stream localFile = new FileStream(_sPath + _filename, FileMode.OpenOrCreate))
            {
                //ms.ToArray()转换为字节数组就是想要的图片源字节
                localFile.Write(ms.ToArray(), 0, (int)ms.Length);
            }
            return _sPath + _filename;
        }

        /// <summary>
        /// 数据流保存成文件
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="filename">文件路径+文件名</param>
        public bool WriteFile(System.IO.Stream stream, string filename)
        {
            try
            {
                using (System.IO.StreamWriter objwrite = new System.IO.StreamWriter(filename))
                {
                    int k = 0;
                    while (k != -1)
                    {
                        k = stream.ReadByte();
                        if (k != -1)
                        {
                            objwrite.BaseStream.WriteByte((byte)k);
                        }
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
